<template>
  <PageWrapper>
    <a-row :gutter="12">
      <a-col :span="8">
        <a-card :bordered="false">
          <template #title>
            <a-space>
              <a-button type="outline" icon-placement="left" @click="openCreateDrawer">
                添加菜单
                <template #icon>
                  <div class="flex items-center">
                    <a-icon size="14">
                      <FileAddOutlined />
                    </a-icon>
                  </div>
                </template>
              </a-button>

              <a-button type="primary" icon-placement="left" @click="packHandle">
                全部{{ expandedKeys.length ? '收起' : '展开' }}
                <template #icon>
                  <div class="flex items-center">
                    <a-icon size="14">
                      <AlignLeftOutlined />
                    </a-icon>
                  </div>
                </template>
              </a-button>
            </a-space>
          </template>
          <div class="w-full menu">
            <a-input v-model="searchKey" placeholder="输入菜单名称搜索">
              <template #suffix>
                <a-icon size="18" class="cursor-pointer">
                  <SearchOutlined />
                </a-icon>
              </template>
            </a-input>
            <div class="py-3 menu-list">
              <template v-if="loading">
                <div class="flex items-center justify-center py-4">
                  <a-spin :size="32" />
                </div>
              </template>
              <template v-else>
                <a-tree
                  :virtual-scroll="true"
                  :data="treeData"
                  :fieldNames="{
                    key: 'key',
                    title: 'label',
                  }"
                  :expandedKeys="expandedKeys"
                  :virtualListProps="{
                    height: 650,
                  }"
                  @update:selected-keys="selectedTree"
                  @update:expanded-keys="onExpandedKeys"
                >
                  <template #title="nodeData">
                    <template v-if="((index = getMatchIndex(nodeData?.label)), index < 0)">{{
                      nodeData?.label
                    }}</template>
                    <span v-else>
                      {{ nodeData?.label?.substr(0, index) }}
                      <span style="color: var(--color-primary-light-4)">
                        {{ nodeData?.label?.substr(index, searchKey.length) }} </span
                      >{{ nodeData?.label?.substr(index + searchKey.length) }}
                    </span>
                  </template>
                </a-tree>
              </template>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :span="16">
        <a-card :bordered="false">
          <template #title>
            <a-space>
              <span>编辑{{ getTypeMsg }}{{ treeItemTitle ? `：${treeItemTitle}` : '' }}</span>
              <a-divider vertical />
              <a-typography-text type="secondary" class="text-sm">
                从左侧列表选择一项后，进行编辑
              </a-typography-text>
            </a-space>
          </template>
          <template #extra>
            <a-popconfirm
              :content="`确定要删除 {{ treeItemTitle }} {{ getTypeMsg }}吗？`"
              @ok="handleDeleteMenu"
              v-if="isEditMenu"
            >
              <a-button type="primary" status="danger">删除{{ getTypeMsg }}</a-button>
            </a-popconfirm>
          </template>
          <!-- 表单 -->
          <a-spin :show="loadingR" class="w-full">
            <MenuForm
              ref="menuFormRef"
              :permissionList="treeData"
              @change="menuChange"
              class="w-2/4 ml-10"
              isShowSubmit
            />
          </a-spin>
        </a-card>
      </a-col>
    </a-row>
    <CreateDrawer
      ref="createDrawerRef"
      :title="drawerTitle"
      :permissionList="treeData"
      @change="menuChange"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, unref, onMounted, computed } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { AlignLeftOutlined, SearchOutlined, FileAddOutlined } from '@vicons/antd';
  import { menuInfo, deleteMenu } from '@/api/system/menu';
  import { permissionList } from '@/api/system/role';
  import { getTreeItem } from '@/utils';
  import CreateDrawer from './CreateDrawer.vue';
  import MenuForm from './MenuForm.vue';

  const createDrawerRef = ref();

  let treeItemKey = ref([]);

  let expandedKeys = ref([]);

  const treeData = ref([]);

  const loading = ref(true);
  const loadingR = ref(false);

  const isEditMenu = ref(false);
  const treeItemTitle = ref('');
  const searchKey = ref('');
  const drawerTitle = ref('');
  const menuFormRef = ref();

  const menuTypeMsg = ref(['目录', '菜单', '按钮']);

  const formParams = ref({
    id: null,
    parentId: 0,
    activeMenu: '',
    affix: false,
    alwaysShow: true,
    icon: '',
    isCache: 1,
    isFrame: 1,
    isVisible: 0,
    menuName: '',
    menuType: 0,
    openType: 1,
    status: 0,
    orderNum: null,
    permissionCode: '',
    permissionName: '',
    query: '',
    routeUrl: '',
    routeName: '',
    component: '',
    redirect: '',
  });

  const getTypeMsg = computed(() => {
    return menuTypeMsg.value[formParams.value.menuType];
  });

  function getMatchIndex(title) {
    if (!searchKey.value) return -1;
    return title.toLowerCase().indexOf(searchKey.value.toLowerCase());
  }

  function handleDeleteMenu() {
    deleteMenu({ permissionId: formParams.value.id }).then(() => {
      Message.success('删除成功');
      isEditMenu.value = false;
      treeItemTitle.value = '';
      menuFormRef.value.handleReset();
      getPermissionList();
    });
  }

  function openCreateDrawer() {
    drawerTitle.value = '添加菜单';
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  }

  async function selectedTree(keys) {
    if (keys.length) {
      const treeItem = getTreeItem(unref(treeData), keys[0]);
      treeItemKey.value = keys;
      treeItemTitle.value = treeItem.label;
      loadingR.value = true;
      const info = await menuInfo({ permissionId: keys[0] });
      const newMenuInfo = {
        id: info.id,
        parentId: info.parentId,
        activeMenu: info.activeMenu,
        affix: info.affix,
        alwaysShow: info.alwaysShow,
        component: info.component,
        icon: info.icon,
        isCache: info.isCache,
        isFrame: info.isFrame,
        isVisible: parseInt(info.visible),
        menuName: info.menuName,
        menuType: info.menuType,
        openType: info.openType,
        status: parseInt(info.status),
        orderNum: info.orderNum,
        permissionCode: info.permissionCode,
        permissionName: info.permissionName,
        query: info.query,
        routeUrl: info.routeUrl,
        routeName: info.routeName,
        redirect: info.redirect,
        frameSrc: info.frameSrc,
        isRoot: info.isRoot,
      };
      formParams.value = newMenuInfo;
      menuFormRef.value.setData(newMenuInfo);
      isEditMenu.value = true;
      loadingR.value = false;
    } else {
      isEditMenu.value = false;
      treeItemKey.value = [];
      treeItemTitle.value = '';
    }
  }

  function packHandle() {
    if (expandedKeys.value.length) {
      expandedKeys.value = [];
    } else {
      expandedKeys.value = unref(treeData).map((item: any) => item.key as string) as [];
    }
  }

  async function getPermissionList() {
    loading.value = true;
    const list = await permissionList();
    treeData.value = list;
    loading.value = false;
  }

  async function menuChange() {
    getPermissionList();
    treeItemTitle.value = '';
    isEditMenu.value = false;
  }

  onMounted(async () => {
    getPermissionList();
  });

  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }
</script>

<style lang="less" sctep></style>
